﻿using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WPF自由布局.ViewModels;

namespace WPF自由布局.Views
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public Dictionary<string, ObservableCollection<SensorViewModel>> RegionData { get; private set; }
        private Dictionary<string, string> previousContentTypes { get; set; }

        public MainWindow()
        {
            InitializeComponent();
            RegionData = new Dictionary<string, ObservableCollection<SensorViewModel>>();
            previousContentTypes = new Dictionary<string, string>();
        }

        // =================== 数据源拖动 相关方法 ===================
        private void ListBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var listBox = sender as ListBox;
            var item = FindAncestor<ListBoxItem>((DependencyObject)e.OriginalSource);
            if (item != null)
            {
                var data = item.DataContext as SensorViewModel;
                DragDrop.DoDragDrop(listBox, data, DragDropEffects.Move);
            }
        }
        private static T FindAncestor<T>(DependencyObject current) where T : DependencyObject
        {
            while (current != null)
            {
                if (current is T)
                {
                    return (T)current;
                }
                current = VisualTreeHelper.GetParent(current);
            }
            return null;
        }
        public void Region_DragOver(object sender, DragEventArgs e)
        {
            e.Effects = e.Data.GetDataPresent(typeof(SensorViewModel)) ? DragDropEffects.Move : DragDropEffects.None;
            e.Handled = true;
        }
        public void SensorList_DragOver(object sender, DragEventArgs e)
        {
            e.Effects = e.Data.GetDataPresent(typeof(SensorViewModel)) ? DragDropEffects.Move : DragDropEffects.None;
            e.Handled = true;
        }
        private void Region_Drop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof(SensorViewModel)))
            {
                var sensorData = e.Data.GetData(typeof(SensorViewModel)) as SensorViewModel;
                var targetRegion = sender as Border;

                if (targetRegion != null && sensorData != null)
                {
                    AddDataToRegion(targetRegion, sensorData); // 将数据添加到区域管理器
                    //AddOrUpdateDataRegion(targetRegion, sensorData); // 更新 DataGrid 行
                }
            }
        }

        // =================== 区域数据 相关方法 ===================
        public void AddDataToRegion(Border region, SensorViewModel sensorData)
        {
            if (!RegionData.ContainsKey(region.Name))
            {
                RegionData[region.Name] = new ObservableCollection<SensorViewModel>();
            }

            // 检查是否已经存在相同名称的 SensorViewModel
            if (!RegionData[region.Name].Any(item => item.SensorName == sensorData.SensorName))
            {
                RegionData[region.Name].Add(sensorData);

                if (region.Child is DraggableDataGrid draggableDataGrid)
                {
                    draggableDataGrid.ItemsSource = RegionData[region.Name];
                }

                if (region.Child is BodePlotControl bodePlotControl)
                {
                    bodePlotControl.ItemsSource = RegionData[region.Name];
                }

                if (region.Child is BodeBindableControl bodeBindableControl) 
                {
                    bodeBindableControl.SetBinding(BodeBindableControl.ItemsSourceProperty, new Binding($"RegionData[{region.Name}]"));
                }
            }


        }
        // =================== 区域布局 相关方法 ===================
        private void LayoutComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (LayoutComboBox.SelectedItem is ComboBoxItem selectedItem)
            {
                ClearMainGrid(MainGrid);    // 清除现有布局

                switch (selectedItem.Content.ToString())
                {
                    case "三格：上 2 下 1":
                        SetThreeRegionLayoutTop(MainGrid);
                        break;
                    case "三格：下 2 上 1":
                        SetThreeRegionLayoutBottom(MainGrid);
                        break;
                    case "四格：2x2":
                        SetFourRegionLayout(MainGrid);
                        break;
                    case "五格：上 3 下 2":
                        SetFiveRegionLayoutThreeOnTop(MainGrid);
                        break;
                    case "五格：上 2 下 3":
                        SetFiveRegionLayoutTwoOnTop(MainGrid);
                        break;
                }

                // 更新每个区域的内容，使用上一次内容类型
                foreach (var child in GetAllBorders(MainGrid))
                {
                    if (previousContentTypes.TryGetValue(child.Name, out var previousContentType))
                    {
                        UpdateRegionContent(child, previousContentType);
                    }
                }
            }
        }
        private IEnumerable<Border> GetAllBorders(DependencyObject parent)
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);

                if (child is Border border)
                {
                    yield return border;
                }
                foreach (var subChild in GetAllBorders(child))
                {
                    yield return subChild;
                }
            }
        }

        private void ClearMainGrid(Grid mainGrid)
        {
            foreach (var child in MainGrid.Children.OfType<Border>())
            {
                if (child.Child is IDisposable oldControl) oldControl.Dispose();
                child.Child = null;
            }
            mainGrid.Children.Clear();
        }

        public void SetThreeRegionLayoutTop(Grid mainGrid)
        {
            // 嵌套的上部Grid
            var topGrid = new Grid();
            topGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
            topGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(5, GridUnitType.Pixel) });
            topGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });

            CreateRegion(topGrid, "region1", 0, 0);
            CreateRegion(topGrid, "region2", 0, 2);

            AddGridSplitter(topGrid, 0, 1, GridResizeDirection.Columns);

            Grid.SetRow(topGrid, 0);
            mainGrid.Children.Add(topGrid);

            // 下部单个区域
            CreateRegion(mainGrid, "region3", 2, 0, 3);

            // 主分隔线在中间
            AddGridSplitter(mainGrid, 1, 0, GridResizeDirection.Rows);
        }

        public void SetThreeRegionLayoutBottom(Grid mainGrid)
        {
            ClearMainGrid(mainGrid);

            // 上部单个区域
            CreateRegion(mainGrid, "region1", 0, 0, 3);

            // 嵌套的下部Grid
            var bottomGrid = new Grid();
            bottomGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
            bottomGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(5, GridUnitType.Pixel) });
            bottomGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });

            CreateRegion(bottomGrid, "region2", 0, 0);
            CreateRegion(bottomGrid, "region3", 0, 2);

            AddGridSplitter(bottomGrid, 0, 1, GridResizeDirection.Columns);

            Grid.SetRow(bottomGrid, 2);
            mainGrid.Children.Add(bottomGrid);

            // 主分隔线在中间
            AddGridSplitter(mainGrid, 1, 0, GridResizeDirection.Rows);
        }

        public void SetFourRegionLayout(Grid mainGrid)
        {
            ClearMainGrid(mainGrid);

            // 嵌套的上部Grid
            var topGrid = new Grid();
            topGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
            topGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(5, GridUnitType.Pixel) });
            topGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });

            CreateRegion(topGrid, "region1", 0, 0);
            CreateRegion(topGrid, "region2", 0, 2);

            AddGridSplitter(topGrid, 0, 1, GridResizeDirection.Columns);

            Grid.SetRow(topGrid, 0);
            mainGrid.Children.Add(topGrid);

            // 嵌套的下部Grid
            var bottomGrid = new Grid();
            bottomGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
            bottomGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(5, GridUnitType.Pixel) });
            bottomGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });

            CreateRegion(bottomGrid, "region3", 0, 0);
            CreateRegion(bottomGrid, "region4", 0, 2);

            AddGridSplitter(bottomGrid, 0, 1, GridResizeDirection.Columns);

            Grid.SetRow(bottomGrid, 2);
            mainGrid.Children.Add(bottomGrid);

            // 主分隔线在中间
            AddGridSplitter(mainGrid, 1, 0, GridResizeDirection.Rows);
        }

        public void SetFiveRegionLayoutThreeOnTop(Grid mainGrid)
        {
            ClearMainGrid(mainGrid);

            // 上部嵌套Grid（3列）
            var topGrid = new Grid();
            topGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
            topGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(5, GridUnitType.Pixel) });
            topGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
            topGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(5, GridUnitType.Pixel) });
            topGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });

            CreateRegion(topGrid, "region1", 0, 0);
            CreateRegion(topGrid, "region2", 0, 2);
            CreateRegion(topGrid, "region3", 0, 4);

            AddGridSplitter(topGrid, 0, 1, GridResizeDirection.Columns);
            AddGridSplitter(topGrid, 0, 3, GridResizeDirection.Columns);

            Grid.SetRow(topGrid, 0);
            mainGrid.Children.Add(topGrid);

            // 下部嵌套Grid（2列）
            var bottomGrid = new Grid();
            bottomGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
            bottomGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(5, GridUnitType.Pixel) });
            bottomGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });

            CreateRegion(bottomGrid, "region4", 0, 0);
            CreateRegion(bottomGrid, "region5", 0, 2);

            AddGridSplitter(bottomGrid, 0, 1, GridResizeDirection.Columns);

            Grid.SetRow(bottomGrid, 2);
            mainGrid.Children.Add(bottomGrid);

            // 主分隔线在中间
            AddGridSplitter(mainGrid, 1, 0, GridResizeDirection.Rows);
        }

        public void SetFiveRegionLayoutTwoOnTop(Grid mainGrid)
        {
            ClearMainGrid(mainGrid);

            // 上部嵌套Grid（2列）
            var topGrid = new Grid();
            topGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
            topGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(5, GridUnitType.Pixel) });
            topGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });

            CreateRegion(topGrid, "region1", 0, 0);
            CreateRegion(topGrid, "region2", 0, 2);

            AddGridSplitter(topGrid, 0, 1, GridResizeDirection.Columns);

            Grid.SetRow(topGrid, 0);
            mainGrid.Children.Add(topGrid);

            // 下部嵌套Grid（3列）
            var bottomGrid = new Grid();
            bottomGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
            bottomGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(5, GridUnitType.Pixel) });
            bottomGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
            bottomGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(5, GridUnitType.Pixel) });
            bottomGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });

            CreateRegion(bottomGrid, "region3", 0, 0);
            CreateRegion(bottomGrid, "region4", 0, 2);
            CreateRegion(bottomGrid, "region5", 0, 4);

            AddGridSplitter(bottomGrid, 0, 1, GridResizeDirection.Columns);
            AddGridSplitter(bottomGrid, 0, 3, GridResizeDirection.Columns);

            Grid.SetRow(bottomGrid, 2);
            mainGrid.Children.Add(bottomGrid);

            // 主分隔线在中间
            AddGridSplitter(mainGrid, 1, 0, GridResizeDirection.Rows);
        }

        private void CreateRegion(Grid parentGrid, string name, int row, int column, int columnSpan = 1)
        {

            Border border = new Border
            {
                BorderBrush = Brushes.Transparent,
                BorderThickness = new Thickness(0),
                Background = Brushes.LightGray,
                Margin = new Thickness(5),
                AllowDrop = true,
            };
            border.Name = name;
            border.MouseRightButtonDown += (sender, e) => Region_MouseRightButtonDown(sender, e);
            border.Drop += (sender, e) => Region_Drop(sender, e);
            border.DragOver += (sender, e) => Region_DragOver(sender, e);
                border.Child = new TextBlock
                {
                    Text = "Please choose the control!",
                    HorizontalAlignment = HorizontalAlignment.Center,
                    VerticalAlignment = VerticalAlignment.Center
                };
            Grid.SetRow(border, row);
            Grid.SetColumn(border, column);
            Grid.SetColumnSpan(border, columnSpan);
            parentGrid.Children.Add(border);
        }


        private void AddGridSplitter(Grid parentGrid, int row, int column, GridResizeDirection direction)
        {
            GridSplitter splitter = new GridSplitter
            {
                Opacity = 0.5,
                ResizeDirection = direction,
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment = VerticalAlignment.Stretch,
                Width = direction == GridResizeDirection.Columns ? 5 : double.NaN,
                Height = direction == GridResizeDirection.Rows ? 5 : double.NaN
            };
            Grid.SetRow(splitter, row);
            Grid.SetColumn(splitter, column);
            parentGrid.Children.Add(splitter);
        }

        // =================== ContextMenu 相关方法 ===================
        private void Region_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            Border selectedRegion = sender as Border;
            ContextMenu contextMenu = CreateContextMenu(selectedRegion);
            selectedRegion.ContextMenu = contextMenu;
            contextMenu.IsOpen = true;
        }

        private ContextMenu CreateContextMenu(Border region)
        {
            ContextMenu contextMenu = new ContextMenu();
            MenuItem nyquistPlotItem = new MenuItem { Header = "奈氏图" };
            nyquistPlotItem.Click += (s, args) => UpdateRegionContent(region, "奈氏图");
            MenuItem dataTableItem = new MenuItem { Header = "自定义控件" };
            dataTableItem.Click += (s, args) => UpdateRegionContent(region, "自定义控件");
            MenuItem bodePlotItem = new MenuItem { Header = "自定义波特" };
            bodePlotItem.Click += (s, args) => UpdateRegionContent(region, "自定义波特");
            MenuItem bodeBindableItem = new MenuItem { Header = "自定义binding波特" };
            bodeBindableItem.Click += (s, args) => UpdateRegionContent(region, "自定义binding波特");
            contextMenu.Items.Add(bodePlotItem);
            contextMenu.Items.Add(nyquistPlotItem);
            contextMenu.Items.Add(dataTableItem);
            contextMenu.Items.Add(bodeBindableItem);
            return contextMenu;
        }

        private void UpdateRegionContent(Border region, string contentType)
        {
           
            // 保存上一次内容类型
            if (previousContentTypes.ContainsKey(region.Name))
            {
                previousContentTypes[region.Name] = contentType;
            }
            else
            {
                previousContentTypes.Add(region.Name, contentType);
            }

            RegionData.TryGetValue(region.Name, out var sensorDataList);

            

            if (region.Child is IDisposable oldControl)oldControl.Dispose();
            
            region.Child = null;

            switch (contentType)
            {
                case "奈氏图":
                    region.Child = new TextBlock
                    {
                        Text = contentType,
                        HorizontalAlignment = HorizontalAlignment.Center,
                        VerticalAlignment = VerticalAlignment.Center
                    };
                    break;
                case "自定义控件":
                    DraggableDataGrid draggableDataGrid = new DraggableDataGrid() { };
                    region.Child = draggableDataGrid;
                    // 获取区域数据并填充到 DataGrid
                    if (sensorDataList != null)
                    {
                        draggableDataGrid.ItemsSource = sensorDataList;
                    }
                    break;

                case "自定义波特":
                    BodePlotControl bodePlotControl = new BodePlotControl() { };
                    region.Child = bodePlotControl;
                    // 获取区域数据并填充到 DataGrid
                    if (sensorDataList != null)bodePlotControl.ItemsSource = sensorDataList;
                    break;

                case "自定义binding波特":
                    BodeBindableControl bodeBindableControl = new BodeBindableControl() { };
                    region.Child = bodeBindableControl;
                    // 获取区域数据并填充到 DataGrid
                    if (sensorDataList != null) bodeBindableControl.SetBinding(BodeBindableControl.ItemsSourceProperty, new Binding($"RegionData[{region.Name}]"));
                    break;
            }
        }
    }
}
